/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.interceptor;

import yhao.infra.apilist.JsonCommonCodeEnum;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 内部请求ip限制拦截器
 *
 * <p>用在微服务之间的调用，仅允许内网ip访问
 *
 * @author yoara
 */
public class InnerAccessCheckInterceptor extends ZBaseInterceptorAdapter {
    private Logger visitLog = LoggerFactory.getLogger(this.getClass());
    private boolean proEnv;
    private String idPrefix = "10.251.92.";

    public InnerAccessCheckInterceptor(boolean proEnv) {
        this.proEnv = proEnv;
    }

    public void setIdPrefix(String idPrefix) {
        this.idPrefix = idPrefix;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        try {
            ResponseBody body = new ResponseBody();
            if(!proEnv){
                return super.preHandle(request, response, handler);
            }
            if (!checkIp(request)) {
                body.setCode(JsonCommonCodeEnum.E0017);
                String ips = StringUtils.join(getIpAddr(request), ",");
                body.setMessage(ips + body.getMessage());
                visitLog.error(body.getMessage());
                printJsonMsg(response, body);
                return false;
            }
            return super.preHandle(request, response, handler);
        } catch (Exception e) {
            visitLog.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

    private boolean checkIp(HttpServletRequest request) {
        String[] ips = getIpAddr(request);
        for(String ip:ips){
            if(ip.trim().startsWith(idPrefix)){
                return true;
            }
        }
        return false;
    }
}
